package utils

import (
	"github.com/golang-jwt/jwt"
	"github.com/yeahyf/go_base/cfg"
	"github.com/yeahyf/go_base/ept"
	"github.com/yeahyf/go_base/log"
	"net/http"
	"time"
)

type JwtInfo struct {
	UserId   uint   `json:"user_id,omitempty"`
	UserName string `json:"user_name,omitempty"`
	jwt.StandardClaims
}

func GetToken(id uint, name string) string {
	info := &JwtInfo{UserId: id, UserName: name}
	info.ExpiresAt = time.Now().Add(time.Second * time.Duration(cfg.GetInt("jwt.expire.time"))).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, info)
	mySignature := []byte(cfg.GetString("jwt.signature.key"))
	signedString, err := token.SignedString(mySignature)
	if err != nil {
		log.Error(err)
		return ""
	}
	return signedString
}

func ParseToken(token string) (*JwtInfo, error) {
	claims, err := jwt.ParseWithClaims(token, &JwtInfo{}, func(token *jwt.Token) (interface{}, error) {
		mySignature := []byte(cfg.GetString("jwt.signature.key"))
		return mySignature, nil
	})
	if err != nil {
		return nil, err
	}
	if info, ok := claims.Claims.(*JwtInfo); ok && claims.Valid {
		return info, nil
	} else {
		return nil, ept.New(http.StatusUnauthorized, "token无效请重新登录")
	}
}
